<template>

</template>

<script>
export default {
  name: "CreateWebScoket",
  methods:{
    creatSocket() {
      let that = this;
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");
        //实例化websocket
        that.ws = new WebSocket("ws://localhost:8182/api/pushMessage/1");
        //保存设置全局websocket对象
        that.$global.setWs(that.ws);
        //监听websocket连接打开方法
        that.ws.onopen = function() {
          console.log("打开websocket")
          //调用keepalive方法（不一定都需要调用此方法，可注释）
          //that.keepAlive()
        }
        //监听websocket错误方法
        that.ws.onerror = function(ev) {
          console.log("连接已出错...");
          //延迟执行重连
          setTimeout(() => {
            that.creatSocket();
          }, that.$global.delay);
        };
        //监听websocket关闭方法
        that.ws.onclose = function(ev) {
          // 关闭 websocket
          console.log("连接已关闭...");
          //延迟执行重连
          setTimeout(() => {
            that.creatSocket();
          }, that.$global.delay);
        };

        //监听websocket接收消息事件（接收来自服务器的实时消息）
        that.ws.onmessage = function(res) {
          console.log("App.vue收到服务器内容", res.data);
        };

      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
      }
    },
    keepAlive(){
      let that = this;
      setTimeout(() => {
        //判断当前webscokt状态
        if(that.$global.ws.readyState == 1){
          console.log('发送keepalve')
          //调用发送方法
          that.$global.sendMsg({
            "type":"keepalive"
          })
          that.keepAlive()
        }
      }, 10000);
    },

  }
}
</script>

<style scoped>

</style>